# 生成我们的图片验证码
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import random
import string


class ImageCode:
    def make_code(self):
        # 生成一个随机的验证码
        # code = random.sample(string.digits + string.ascii_letters, 4)
        code = random.sample(string.digits, 4)

        return code

    def make_code_image(self, code_str):
        # 生成了一个空白的图
        image = Image.new("RGB", (135, 40), "lightblue")

        # 生成画笔
        draw = ImageDraw.Draw(image)

        # 创建字体样式
        font = ImageFont.truetype(font=r"C:\Windows\Fonts\arial.ttf", size=30)

        for i in range(len(code_str)):
            # 绘制
            draw.text((i * 35 + 5, 5), code_str[i], fill="black", font=font)

        bytes_image = BytesIO()
        image.save(bytes_image, format="png")

        # 返回图片的字节流
        return bytes_image.getvalue()
        # # 生成了一个空白的图
        # image = Image.new("RGB", (135, 40), "lightblue")
        #
        # # 生成画笔
        # draw = ImageDraw.Draw(image)
        #
        # # 创建字体样式
        # font = ImageFont.truetype(font=r"C:\Windows\Fonts\arial.ttf", size=30)
        #
        # for i in range(len(code_str)):
        #     # 绘制
        #     draw.text((i * 35 + 5, 5), code_str[i], fill="black", font=font)
        #
        # bytes_image = BytesIO()
        # image.save(bytes_image, format="png")
        #
        # # 返回图片的字节流
        # return bytes_image.getvalue()

